package com.qianchang.microfinance.view.register;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.InputType;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.TokenManager;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.DMLog;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.MD5Util;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.RoundImageView;
import com.dm.library.widgets.element.DButton;
import com.dm.library.widgets.element.DTextView;
import com.dm.library.widgets.statusbar.StatusBarUtil;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.FindUserBasicInfoBean;
import com.qianchang.microfinance.bean.UserLoginInfo;
import com.qianchang.microfinance.bean.event.AgreementTitleBean;
import com.qianchang.microfinance.bean.event.LoginEvent;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.utils.IdentifyCode;
import com.qianchang.microfinance.utils.SpanUtils;
import com.qianchang.microfinance.view.MainActivity;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.credit.data.ScanIdentityActivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.qianchang.microfinance.global.ConstantAppInfo.DEFAULT_TIME;


public class RegisterActivity extends BaseActivity {


    private static final String TAG = "RegisterActivity";
    public static final String REGISTER_DATA = "register_data";
    public static final String KEY_PHONE = "KEY_PHONE";
    @BindView(R.id.et_input_account)
    EditText etInputAccount;
    @BindView(R.id.et_phone_indentify_code)
    EditText etPhoneIndentifyCode;
    @BindView(R.id.tv_get_phone_code)
    DTextView tvGetPhoneCode;
    @BindView(R.id.et_input_password)
    EditText etInputPassword;
    @BindView(R.id.iv_pwd_visible)
    CheckBox ivPwdVisible;
    @BindView(R.id.et_input_checkcode)
    EditText etInputCheckcode;
    @BindView(R.id.iv_checkcode)
    RoundImageView ivCheckcode;
    @BindView(R.id.ll_checkcode)
    LinearLayout llCheckcode;
    @BindView(R.id.ll_identify_code)
    LinearLayout llIdentifyCode;
    @BindView(R.id.tv_register)
    DButton tvRegister;
    @BindView(R.id.tv_protocol)
    DTextView tvProtocol;
    @BindView(R.id.ck_protocol)
    CheckBox cbProtocol;
    @BindView(R.id.tv_title)
    DTextView tvTitle;
    @BindView(R.id.tv_back)
    DTextView tvBack;
    @BindView(R.id.tv_right)
    DTextView tvRight;
    @BindView(R.id.title_bar)
    RelativeLayout titleBar;
    private boolean agreementCheck;
    private CountDownTimer phoneDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        StatusBarUtil.setTranslucentForImageViewInFragment(RegisterActivity.this, null);
        ButterKnife.bind(this);
        initView();
        initData();
        showIdentifyCode();//test
    }

    //更新验证码 并显示
    private void showIdentifyCode() {
        ivCheckcode.setImageBitmap(IdentifyCode.getInstance(this).createBitmap());
    }

    @Override
    protected void initView() {
        super.initView();
        cbProtocol.setText(getString(R.string.Label_reading));
        tvTitle.setText(getString(R.string.Label_register));
        Drawable drawable = getResources().getDrawable(R.drawable.back);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        tvBack.setCompoundDrawables(drawable, null, null, null);

    }

    @Override
    protected void initData() {
        super.initData();
        setTitleName(getString(R.string.Label_register));
        //pwd  show  hide
        ivPwdVisible.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int length = etInputPassword.getText().length();
                if (isChecked) {
                    etInputPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    etInputPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                etInputPassword.setSelection(length);
            }
        });

        JSONArray js = new JSONArray();
        js.put("6");
        js.put("11");

        AgreementApi.getAgreementName(this, js, new AgreementApi.AgreementNameCallBack() {
            @Override
            public void success(List<AgreementTitleBean> agreementTitleList) {
                if (null != agreementTitleList && !agreementTitleList.isEmpty()) {

//                    tvProtocol.setTextContent("《" + agreementTitleList.get(0).getAgreementName() + "》");


                    AgreementTitleBean agreementOne = agreementTitleList.get(0);
                    AgreementTitleBean agreementTwo = agreementTitleList.get(1);

                    tvProtocol.setMovementMethod(LinkMovementMethod.getInstance());
                    tvProtocol.setHighlightColor(getResources().getColor(android.R.color.transparent));
                    SpanUtils spanUtils = new SpanUtils();
                    spanUtils.append("《" + agreementOne.getAgreementName() + "》")
                            .setClickSpan(new ClickableSpan() {
                                @Override
                                public void onClick(View widget) {
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable(ConstantAppInfo.AGREEMENT_ID, "6");
                                    startActivity(AgreementActivity.class, bundle);
                                }

                                @Override
                                public void updateDrawState(TextPaint ds) {
                                    ds.setColor(getResources().getColor(R.color.common_blue_color_light));
                                    ds.setUnderlineText(false);
                                }
                            })

                            .append("《" + agreementTwo.getAgreementName() + "》")
                            .setClickSpan(new ClickableSpan() {
                                @Override
                                public void updateDrawState(TextPaint ds) {
                                    ds.setColor(getResources().getColor(R.color.common_blue_color_light));
                                    ds.setUnderlineText(false);
                                }

                                @Override
                                public void onClick(View widget) {
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable(ConstantAppInfo.AGREEMENT_ID, "11");
                                    startActivity(AgreementActivity.class, bundle);
                                }
                            });
                    tvProtocol.setText(spanUtils.create());
                }
            }
        });
    }

    @OnClick({R.id.tv_get_phone_code, R.id.iv_pwd_visible, R.id.tv_protocol, R.id.tv_title, R.id.tv_register,R.id.tv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_get_phone_code:    //获取校验码
                getPhoneCode();
                break;
            case R.id.iv_pwd_visible:
                break;
            case R.id.tv_register:  //校验并注册
                checkAndRegister();
                break;
            case R.id.tv_protocol:  //跳转至协议界面
                Bundle bundle = new Bundle();
                bundle.putSerializable(ConstantAppInfo.AGREEMENT_ID, "6");
//                bundle.putSerializable(ConstantAppInfo.AGREEMENT_ID, "7");      //测试使用
                startActivity(AgreementActivity.class, bundle);
                break;
            case R.id.tv_title:
                break;
            case R.id.tv_back:  //返回
                EventBus.getDefault().post(new LoginEvent(LoginEvent.LoginStatue.LOGIN_FAILED));
                finish();
                break;
        }
    }

    private void checkAndRegister() {
        String strAccount = etInputAccount.getText().toString().trim();
        String strPwd = etInputPassword.getText().toString().trim();
        String phoneIdentifyCode = etPhoneIndentifyCode.getText().toString().trim();

        if (!FormatUtil.isValidPhone(strAccount, null)) {// PHONE_REGEX   手机号正则的key
            ToastUtil.getInstant().show(RegisterActivity.this, getString(R.string.msg_input_correct_account));
            return;
        }

        //检查手机短信验证码是否为空
        if (phoneIdentifyCode.length() == 0) {
            ToastUtil.getInstant().show(RegisterActivity.this, getString(R.string.regist_phone_identify_code_not_ok));
            return;
        }
        if (!FormatUtil.isValidPassword(strPwd, null)) {
            ToastUtil.getInstant().show(RegisterActivity.this, getString(R.string.msg_pwd_not_ok));
            return;
        }
        if(!cbProtocol.isChecked()){
            ToastUtil.getInstant().show(RegisterActivity.this, getString(R.string.msg_read_loan_agreement));
            return;
        }
        //校验通过后注册
        register(strAccount, strPwd, phoneIdentifyCode);

    }

    /**
     * 注册
     * @param strAccount 用户名
     * @param strPwd 密码
     * @param phoneIdentifyCode 验证码
     */
    private void register(final String strAccount, final String strPwd, String phoneIdentifyCode) {
        show();
        HttpParams params = new HttpParams();
        params.put("phone", strAccount);
        params.put("password", MD5Util.string2MD5(strPwd + ConstantAppInfo.Password.PASSWORD_SUFFIX));//ActivityConstants
        params.put("verifyCode", phoneIdentifyCode);
        params.put("channelCore",getString(R.string.channelCore_value));

        DMOKHttpUtils.getInstance().post(getApplicationContext(), DMConstant.ApiURL.REGISTER, params, new RequestCallBack<UserLoginInfo>() {//UserLoginInfo
            @Override
            public void onSuccess(JsonResult<UserLoginInfo> jsonResult) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(jsonResult.getCode())) {
                    //注册成功  跳转登录界面
//                    registerSuccess(jsonResult.getObject());            //2018.1.13注释迪蒙代码

                    regSusJumpScanIdentity(jsonResult.getObject());         //2018.1.13鸿胜科技新增未自己跳转到新的实名认证页面

                } else {
                    ToastUtil.getInstant().show(RegisterActivity.this, jsonResult.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(RegisterActivity.this, msg);
                DMLog.i(TAG, "onFailure: " + msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(RegisterActivity.this, msg);
                DMLog.i(TAG, "onFailure: " + msg);
            }
        });
    }

    /**
     * 登陆成功，跳转登录
     *
     * @param userLoginInfo
     */
    private void registerSuccess(UserLoginInfo userLoginInfo) {//UserLoginInfo
        DMApplication.getInstance().setUserLoginInfo(userLoginInfo);
        TokenManager.getInstance().setToken(RegisterActivity.this, userLoginInfo.getToken());
        startActivity(MainActivity.class, true);
    }


    /**
     * 登陆成功，跳转实名认证页面
     *
     * @param userLoginInfo
     */
    private void regSusJumpScanIdentity(UserLoginInfo userLoginInfo) {  //UserLoginInfo
        Log.i("TAG","获取用户登录信息"+userLoginInfo.toString());
        DMApplication.getInstance().setUserLoginInfo(userLoginInfo);
        TokenManager.getInstance().setToken(RegisterActivity.this, userLoginInfo.getToken());
        EventBus.getDefault().post(new LoginEvent(LoginEvent.LoginStatue.LOGIN_SUC));
        Bundle bundle = new Bundle();
        //跳转至实名认证页面
        startActivity(ScanIdentityActivity.class, bundle,true);
    }




    /**
     * 向 获取手机验证码
     */
    private void getPhoneCode() {
        String s_phone = etInputAccount.getText().toString().trim();
        if (!FormatUtil.isValidPhone(s_phone, null)) {
            ToastUtil.getInstant().show(this, getString(R.string.msg_input_correct_account));
            return;
        }

        if(s_phone.length() >= 3 ){
            String subStr = s_phone.substring(0,3);
            if(subStr.equals("170") || subStr.equals("171") || subStr.equals("145") || subStr.equals("147")){
                ToastUtil.getInstant().show(this, "该手机号无法注册");
                return;
            }
        }

//        checkPhoneExist(s_phone);//不检验手机号是否存在
        sendCaptcha(s_phone);
    }

    //过滤手机号段 170，171，145，147 不能注册
    private void filterPhone(String phone){
        if(phone.length() >= 3 ){
            String subStr = phone.substring(0,3);
            if(subStr.equals("170") || subStr.equals("171") || subStr.equals("145") || subStr.equals("147")){
                ToastUtil.getInstant().show(this, "该手机号无法注册");
                return;
            }
        }
    }


    //显示获取手机验证码倒计时
    private void showRemainTime() {
        tvGetPhoneCode.setEnabled(false);
        phoneDownTimer = new CountDownTimer(DEFAULT_TIME, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                int temp = (int) (millisUntilFinished / 1000);
                tvGetPhoneCode.setText(temp + "S");//getString(R.string.remain_time) +
                tvGetPhoneCode.setEnabled(false);
            }

            @Override
            public void onFinish() {
                tvGetPhoneCode.setText(getString(R.string.btn_get_verify_code));
                tvGetPhoneCode.setEnabled(true);
            }
        }.start();
    }

    /**
     * 发送验证码
     */
    private void sendCaptcha(String s_phone) {
        show();
        HttpParams params = new HttpParams();
        params.put("verifyType", "0");//0 短信；1 邮箱；2：语音
        params.put("phone", s_phone);
        params.put("msgType", "1");//【忘记密码：0、注册:1】
//        params.put("verifyMethod", "1");
        params.put("type", "1");//0 需要校验 1 不需要校验手机号码是否存在
        params.put("busType", "9");//   验证码类型编码  1：注册,2：用户找回登陆密码 9:校验

        DMOKHttpUtils.getInstance().post(getApplicationContext(), DMConstant.ApiURL.SEND_IDENTIFY_CODE, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                Log.i(TAG, response.toString());
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    ToastUtil.getInstant().show(RegisterActivity.this, getString(R.string.msg_indentity_code_send_success));
                    showRemainTime();
                } else {
                    ToastUtil.getInstant().show(RegisterActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(RegisterActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(RegisterActivity.this, msg);
            }

        });
    }


}
